import { inject, onBeforeMount, onMounted, Ref, ref } from 'vue';
import { computed, defineComponent, SetupContext } from 'vue';
import { MemoryVoiceCreateResourceProps, memoryVoiceCreateResourceeProps } from './create-resource.props';
import FDynamicFormGroup from '../../../../dynamic-form/src/component/dynamic-form-group/dynamic-form-group.component';
import './create-resource.scss';
import { userInfo } from '../../composition/use-data';
import { ResourceCategory, ResourceInfo } from '../../composition/types';

export default defineComponent({
    name: 'FMemoryVoiceCreateResource',
    props: memoryVoiceCreateResourceeProps,
    emits: ['success'] as (string[] & ThisType<void>) | undefined,
    setup(props: MemoryVoiceCreateResourceProps, context: SetupContext) {
        const NotifyService: any = inject('NotifyService');

        // 分类列表
        const categoryList = userInfo?.value?.categories || [];

        // 当前选中的分类
        const currentCategory: Ref<ResourceCategory | null> = ref(null);

        const courseEditor = {
            type: 'combo-list',
            placeholder: '请选择科目',
            // data: [],
            valueField: 'id',
            textField: 'title',
            idField: 'id',
            editable: false
        };

        onBeforeMount(() => {
            if (categoryList && categoryList.length) {
                currentCategory.value = categoryList[0];
                courseEditor['data'] = currentCategory.value.courseList || [];
                if (courseEditor['data'] && courseEditor['data'].length) {
                    initialResource.course = courseEditor['data'][0].id;
                }
            }
        });
        // 可选的科目列表--TODO
        // const courseList = computed(() => {
        //     return () => {
        //         const list = currentCategory?.value?.courseList;

        //         if (currentCategory && currentCategory.value) {
        //             return currentCategory.value.courseList;
        //         }
        //         if (categoryList && categoryList.length) {
        //             return categoryList[0].courseList;
        //         }
        //         return [];
        //     };
        // });

        // form-group编辑器信息
        const nameEditor = { type: 'text' };
        // const courseEditor = {
        //     type: 'combo-list',
        //     placeholder: '请选择',
        //     data: courseList || [],
        //     valueField: 'id',
        //     nameField: 'title',
        //     editable: false
        // };

        // 初始资源信息
        const initialResource: ResourceInfo = {
            title: '',
            content: '',
            id: Math.random().toString(36).substring(7),
            course: '',
            overview: ''
        };
        const resourceInfo = ref(initialResource);

        function onResourceContentChange(event) {
            resourceInfo.value.content = event.target.value;
        }
        function onResourceOverviewChange(event) {
            resourceInfo.value.overview = event.target.value;
        }
        /**
         * 保存资料
         */
        function saveResource() {
            const selectedCourse = currentCategory.value?.courseList.find((c) => c.id === resourceInfo.value.course);
            if (selectedCourse) {
                selectedCourse.resourceList.unshift(resourceInfo.value);
                // NotifyService?.show({
                //     showCloseButton: false,
                //     timeout: 3000,
                //     toasts: [{ type: 'success', title: 'This is a title', msg: '资料保存成功' }]  // 这个notify有问题，窗口无法消失。。。
                // });
                context.emit('success');
            }
            // const x;
        }
        var playType = 0;
        var playList = ['title', 'overview', 'content'];
        var utterance: SpeechSynthesisUtterance;
        var isListening = ref(false);

        function testListen() {
            // 这里提供试听功能，试听的内容为resourceInfo.value.content
            playContent(resourceInfo.value[playList[playType]]);
        }
        function endTestListen() {
            if (SpeechSynthesisUtterance) {
                speechSynthesis.cancel();
                isListening.value = false;
            }
        }
        const playContent = (content) => {
            const synth = window.speechSynthesis;
            utterance = new SpeechSynthesisUtterance(content);
            utterance.addEventListener('end', () => {
                playType++;
                if (playType < playList.length) {
                    playContent(resourceInfo.value[playList[playType]]);
                } else {
                    isListening.value = false;
                }
            });
            synth.speak(utterance);
            isListening.value = true;
        };
        /**
         * 切换分类
         */
        function onCategoryTabChanged(newValue: any) {
            currentCategory.value = categoryList.find((c) => c.id === newValue?.nextId) || null;
        }
        return () => {
            return (
                <div class="mv-create">
                    <f-tabs onTabChange={onCategoryTabChanged}>
                        {categoryList?.map((category: ResourceCategory) => {
                            return <f-tab-page id={category.id} title={category.title}></f-tab-page>;
                        })}
                    </f-tabs>
                    <f-section>
                        <div class="f-form-layout farris-form farris-form-controls-inline position-relative">
                            <FDynamicFormGroup
                                customClass="col-12 mb-2"
                                editor={nameEditor}
                                label="资料名称"
                                required={true}
                                id="resource-name"
                                v-model={resourceInfo.value.title}></FDynamicFormGroup>
                            <FDynamicFormGroup
                                customClass="col-12 mb-2"
                                editor={courseEditor}
                                label="资料所属科目"
                                required={true}
                                id="resource-course"
                                v-model={resourceInfo.value.course}></FDynamicFormGroup>
                            <span class="f-icon f-icon-plus-circle create-course-icon" title="新增科目"></span>
                            <div class="col-12 mb-2">
                                <div class="farris-group-wrap">
                                    <div class="form-group farris-form-group">
                                        <label class="col-form-label col-form-label-multi">
                                            <span class="farris-label-info text-danger">*</span>
                                            <span class="farris-label-text"> 资料简述 </span>
                                        </label>
                                        <div class="farris-input-wrap">
                                            <textarea
                                                class="form-control"
                                                id="resource-overview"
                                                maxlength="2000"
                                                style="height:50px"
                                                value={resourceInfo.value.overview}
                                                onInput={onResourceOverviewChange}
                                                placeholder="请输入资料简要说明 "></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 mb-2">
                                <div class="farris-group-wrap">
                                    <div class="form-group farris-form-group">
                                        <label class="col-form-label col-form-label-multi">
                                            <span class="farris-label-info text-danger">*</span>
                                            <span class="farris-label-text"> 资料内容 </span>
                                        </label>
                                        <div class="farris-input-wrap">
                                            <textarea
                                                class="form-control"
                                                id="resource-content"
                                                maxlength="2000"
                                                style="height:200px"
                                                value={resourceInfo.value.content}
                                                onInput={onResourceContentChange}
                                                placeholder="请输入资料内容 "></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="d-flex btn-panel">
                            <button class="btn btn-primary" onClick={saveResource}>
                                保存
                            </button>
                            {isListening.value ? (
                                <button class="btn btn-secondary listen" onClick={() => endTestListen()}>
                                    <img src="assets/memory-voice/end-listen.png"></img>
                                    停止试听
                                </button>
                            ) : (
                                <button class="btn btn-secondary listen" onClick={() => testListen()}>
                                    <img src="assets/memory-voice/listen.png"></img>
                                    试听
                                </button>
                            )}
                        </div>
                    </f-section>
                </div>
            );
        };
    }
});
